package com.cloud.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.cloud.auth.service.ValidateCodeService;
import com.cloud.common.core.base.ApiResponse;
import com.cloud.common.core.base.ApiResponseEnum;
import com.cloud.common.core.base.enums.ApiBaseEnum;
import com.cloud.common.core.exception.BizException;
import com.cloud.common.core.exception.ValidateCodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * @Description:
 * @Auther: zhangxun
 * @Date: 2020/8/7 15:02
 */
@RestController
public class SecurityController {

    @Autowired
    private ConsumerTokenServices consumerTokenServices;
    @Autowired
    private ValidateCodeService validateCodeService;

    @GetMapping("/oauth/test")
    public String testOauth() {
        return "oauth";
    }

    @GetMapping("/user")
    public Principal currentUser(Principal principal) {
        return principal;
    }

    @DeleteMapping("/signout")
    public ApiResponse signout(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        String token = StrUtil.replace(authorization, "bearer ", "");
        if (!consumerTokenServices.revokeToken(token)) {
            throw new BizException(ApiResponseEnum.FAIL,"退出登录失败");
        }
        return ApiResponse.respond("退出登录成功");
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException {
        validateCodeService.create(request, response);
    }
}